import { API_BASE_URL, API_TOKEN } from '../constants';
import type { PaginatedResponse, AccountRead, TransactionRead, CategoryRead, TransactionStore, SingleResponse } from '../types';

const headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': `Bearer ${API_TOKEN}`,
};

async function apiFetch<T,>(endpoint: string, options: RequestInit = {}): Promise<T> {
    const url = `${API_BASE_URL}${endpoint}`;
    
    try {
        const response = await fetch(url, {
            ...options,
            headers: { ...headers, ...options.headers },
        });

        if (!response.ok) {
            const errorBody = await response.text();
            console.error("API Error Response:", errorBody);
            throw new Error(`API error: ${response.status} ${response.statusText}`);
        }

        if (response.status === 204) {
            return null as T;
        }
        return response.json();
    } catch (error) {
        console.error(`Fetch failed for ${url}:`, error);
        throw error;
    }
}

export const getAccounts = () => apiFetch<PaginatedResponse<AccountRead>>('/accounts?type=asset');
export const getTransactions = () => apiFetch<PaginatedResponse<TransactionRead>>('/transactions?page=1&limit=50');
export const getCategories = () => apiFetch<PaginatedResponse<CategoryRead>>('/categories?enabled=true');

export const createTransaction = (data: TransactionStore) => apiFetch<SingleResponse<TransactionRead>>('/transactions', {
    method: 'POST',
    body: JSON.stringify(data),
});

export const updateTransaction = (id: string, data: TransactionStore) => apiFetch<SingleResponse<TransactionRead>>(`/transactions/${id}`, {
    method: 'PUT',
    body: JSON.stringify(data),
});

export const deleteTransaction = (id: string) => apiFetch<null>(`/transactions/${id}`, {
    method: 'DELETE',
});